//导入
const mongoose = require('mongoose');
const fs = require('fs');
//连接
mongoose.connect('mongodb://127.0.0.1:27017/games');

//绑定回调
mongoose.connection.on('open', () => {
  //创建结构对象
  const MovieSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true
    },
    director: {
      type: String,
      required: true
    },
    actors: {
      type: Array
    },
    rate: {
      type: Number,
      default: 0
    },
    pub_time: {
      type: Date
    }
  })

  //创建模型对象
  const MovieModel = mongoose.model('movie', MovieSchema);

  //条件查询
  // MovieModel.find({rate: {$lt: 1}}, (err, data) => {
  //   if(err) throw err;
  //   console.log(data);
  //   //关闭链接
  //   mongoose.disconnect();
  // })

  //逻辑或
  // MovieModel.find({$or: [{rate: {$gt: 9.5}}, {director: '新海城'}]}, (err, data) => {
  //   if(err) throw err;
  //   console.log(data);
  //   //关闭链接
  //   mongoose.disconnect();
  // })

  //逻辑与   "name" : "喜羊羊与灰太狼", "director" : "懒羊羊"
  // MovieModel.find({$and: [{name:'喜羊羊与灰太狼'}, {director: '懒羊羊'}]}, (err, data) => {
  //   if(err) throw err;
  //   console.log(data);
  //   //关闭链接
  //   mongoose.disconnect();
  // })

  //模糊查询   a速度与激情b    速度a与激情b
  MovieModel.find({name: /速度与激情/}, (err, data) => {
    if(err) throw err;
    console.log(data);
    //关闭链接
    mongoose.disconnect();
  })

});


mongoose.connection.on('error', () => {
  console.log('连接失败~~');
});